package com.ben.multiple.shiro;

import com.ben.multiple.shiro.cache.AuthenticationTokenCache;
import com.ben.multiple.shiro.cache.CacheModel;
import com.ben.multiple.shiro.entity.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Collection;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Ben
 * @date 2021/1/31
 */
@RestController
@RequestMapping
@Slf4j
@AllArgsConstructor
public class LoginResource {
    private final AuthenticationTokenCache authenticationTokenCache;

    @PostMapping("/login")
    public String login(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return "请输入用户名和密码！";
        }
        String username = user.getUsername();
        String password = user.getPassword();
        Optional<User> optional = User.USER_LIST.stream().filter(obj -> obj.getUsername().equals(username)).findFirst();
        if (!optional.isPresent()) {
            return "无此用户";
        }
        User entity = optional.get();

        if (!Objects.equals(entity.getPassword(), password)) {
            return "密码错误";
        }

        //生成token， 一天过期
        String token = UUID.randomUUID().toString();
        try {
            String value = new ObjectMapper().writeValueAsString(user);
            CacheModel model = new CacheModel(token, value,
                    System.currentTimeMillis() + 24 * 60 * 60 * 1000);
            authenticationTokenCache.put(token, model);
            log.info("登录：{}", model);
            return token;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return "login fail";
    }

    @GetMapping("/admin")
    public String admin(HttpServletRequest request, HttpServletResponse response) {
        Collection<String> headerNames = response.getHeaderNames();
        Object principal = SecurityUtils.getSubject().getPrincipal();
        System.out.println(principal);
        return "admin success!";
    }

    @RequiresPermissions("p1")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

    @RequiresPermissions("p3")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }
}
